<template>
    <div>
        <div class="color-box table-form">
            <div class="table-title">
                <el-space>
                    <el-button
                        :disabled="isEditing"
                        type="primary"
                        @click="onAddColor"
                    >
                        新增颜色
                    </el-button>
                    <el-button
                        :disabled="isEditing"
                        type="primary"
                        @click="copyYColor"
                        >複制已选颜色外發</el-button
                    >
                    <el-button
                        :disabled="isEditing"
                        type="danger"
                        @click="colorDelete"
                        >删除</el-button
                    >
                    <el-button
                        :disabled="isEditing || eyeColorData1.length > 0"
                        v-if="delType == 'colors1'"
                        type="warning"
                        @click.stop="copyColor"
                        >从设计规格复制</el-button
                    >
                    <el-button
                        :disabled="isEditing || eyeColorData1.length > 0"
                        v-if="delType == 'colors2'"
                        type="warning"
                        @click.stop="copyColor"
                        >从产品规格复制</el-button
                    >
                </el-space>
            </div>

            <el-table
                :data="eyeColorData1"
                ref="multipleTableRef"
                style="width: 100%"
                @selection-change="eyeColorSelectionChange"
                border
            >
                <el-table-column
                    type="selection"
                    :width="'55px'"
                ></el-table-column>
                <el-table-column prop="colorNum" :width="'55px'" label="颜色" />
                <el-table-column
                    prop="customerColorNum"
                    :width="'150px'"
                    :min-width="'150px'"
                    label="客色号"
                >
                    <template #default="scope">
                        <div>
                            <input
                                :maxlength="40"
                                :disabled="isEditing"
                                v-model="scope.row.customerColorNum"
                                @blur="blurTest(scope.row)"
                                placeholder="请输入"
                            />
                            <div
                                v-if="scope.row.err"
                                style="
                                    font-size: 12px;
                                    color: red;
                                    line-height: normal;
                                "
                            >
                                {{ scope.row.err }}
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="customerStyleNum"
                    :width="'150px'"
                    :min-width="'150px'"
                    label="客款号"
                >
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <input
                                :maxlength="40"
                                v-model="scope.row.customerStyleNum"
                                placeholder=""
                                :disabled="isEditing"
                            />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="localColorDesc"
                    label="本厂颜色描述"
                    :width="'240px'"
                    :min-width="'240px'"
                >
                    <template #default="{ row, $index }">
                        <div
                            v-if="
                                props.formData.frameMaterials == '啤架' ||
                                props.formData.frameMaterials == '膠架'
                            "
                        >
                            <input
                                :maxlength="40"
                                v-model="row.localColorDesc"
                                @blur="blurLocalColorDescTest(row)"
                                placeholder=""
                                :disabled="isEditing"
                            />
                            <div
                                v-if="row.errlocaldesc"
                                style="
                                    font-size: 12px;
                                    color: red;
                                    line-height: normal;
                                "
                            >
                                {{ row.errlocaldesc }}
                            </div>
                        </div>
                        <div style="display: flex; align-items: center" v-else>
                            <div
                                @dblclick="generateColorDesc($index, row)"
                                style="
                                    width: 100%;
                                    border: 1px solid #ccc5;
                                    min-height: 24px;
                                    border-radius: 4px;
                                    background: #f5f7fa;
                                    padding: 6px;
                                    box-sizing: border-box;
                                "
                            >
                                <!-- <el-input
                                    :maxlength="40"
                                    v-model="row.localColorDesc"
                                    placeholder=""
                                    disabled
                                /> -->
                                {{ row.localColorDesc }}
                            </div>
                            <el-button
                                type="primary"
                                style="margin-left: 10px"
                                size="small"
                                @click="generateColorDesc($index, row)"
                                :disabled="isEditing"
                                v-if="!row.localColorDesc"
                            >
                                {{ row.localColorDesc ? "查看" : "生成" }}
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="circleColorRequire"
                    label="圈颜色要求"
                    :min-width="'120px'"
                >
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <textarea
                                :title="scope.row.circleColorRequire"
                                v-model="scope.row.circleColorRequire"
                                :disabled="isEditing"
                                @blur="circleColorRequireBlur(scope.row)"
                                placeholder=""
                                rows="2"
                            />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="spleenColorRequire"
                    label="脾颜色要求"
                    :min-width="'120px'"
                >
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <textarea
                                :title="scope.row.spleenColorRequire"
                                v-model="scope.row.spleenColorRequire"
                                @blur="spleenColorRequireBlur(scope.row)"
                                :disabled="isEditing"
                                placeholder=""
                                rows="2"
                            />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="otherColorRequire"
                    label="其它颜色要求"
                    :min-width="'120px'"
                >
                    <template #default="scope">
                        <div style="display: flex; align-items: center">
                            <textarea
                                :title="scope.row.otherColorRequire"
                                v-model="scope.row.otherColorRequire"
                                @blur="otherColorRequireBlur(scope.row)"
                                :disabled="isEditing"
                                placeholder=""
                                rows="2"
                            />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="salesNum"
                    label="销售组织"
                    :width="'150px'"
                    :min-width="'150px'"
                    v-if="
                        props.formData.customerBrand == 'LEVIS' ||
                        props.formData.customerBrand == 'levis' ||
                        props.formData.customerBrand == 'fila' ||
                        props.formData.customerBrand == 'FILA'
                    "
                >
                    <template #default="scope">
                        <el-checkbox-group
                            v-model="scope.row.salesNum"
                            :disabled="isEditing"
                            class="sales-num"
                        >
                            <el-checkbox label="1000" value="1000" />
                            <el-checkbox label="9000" value="9000" />
                        </el-checkbox-group>
                    </template>
                </el-table-column>
                <!-- <el-table-column
                    prop="op"
                    label="操作"
                    width="100"
                >
                    <template #default="{ row, $index }">
                        <el-button
                            type="danger"
                            size="small"
                            @click="onDeleteColor($index)"
                        >
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column> -->
            </el-table>
        </div>
        <!-- 生成本场颜色描述弹窗 -->
        <el-dialog
            v-model="state.colorDescDialogFormVisible"
            title="本厂颜色取号"
            width="800"
            :before-close="colorDescDialogCel"
        >
            <el-form
                :model="state.colorDescForm"
                label-position="top"
                ref="colorDescFormRef"
                :rules="state.colorDescFormRules"
            >
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item
                            label="电镀色编号"
                            prop="electroplatedColorNum"
                        >
                            <el-select
                                v-model="
                                    state.colorDescForm.electroplatedColorNum
                                "
                                :disabled="
                                    state.colorDescForm.isView || isEditing
                                "
                                @change="electroplatedColorNumChange"
                                filterable
                            >
                                <el-option
                                    v-for="item in state.electroplateColorCodeList"
                                    :key="item.PLATE"
                                    :label="item.PLATE"
                                    :value="item.PLATE"
                                />
                                <!-- item.ZDESC -->
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="说明" prop="gradientDesc">
                            <input
                                disabled
                                :maxlength="40"
                                v-model="state.colorDescForm.gradientDesc"
                                :disabled="
                                    state.colorDescForm.isView || isEditing
                                "
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="　" prop="isGradientColor">
                            <el-checkbox
                                v-model="state.colorDescForm.isGradientColor"
                                :disabled="
                                    state.colorDescForm.isView || isEditing
                                "
                                >渐变色</el-checkbox
                            >
                        </el-form-item>
                    </el-col>
                    <!-- <template v-if="state.colorDescForm.isGradientColor"> -->
                    <el-col :span="6">
                        <el-form-item
                            label="間色一(單色)"
                            prop="gradientColor1"
                        >
                            <input
                                :maxlength="40"
                                v-model="state.colorDescForm.gradientColor1"
                                :disabled="
                                    state.colorDescForm.isView || isEditing
                                "
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item
                            label="間色二(單間色)"
                            prop="gradientColor2"
                        >
                            <input
                                :maxlength="40"
                                v-model="state.colorDescForm.gradientColor2"
                                :disabled="
                                    state.colorDescForm.isView || isEditing
                                "
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item
                            label="間色三(雙間色)"
                            prop="gradientColor3"
                        >
                            <input
                                :maxlength="40"
                                v-model="state.colorDescForm.gradientColor3"
                                :disabled="
                                    state.colorDescForm.isView || isEditing
                                "
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item
                            label="間色四(三間色)"
                            prop="gradientColor4"
                        >
                            <input
                                :maxlength="40"
                                v-model="state.colorDescForm.gradientColor4"
                                :disabled="
                                    state.colorDescForm.isView || isEditing
                                "
                            />
                        </el-form-item>
                    </el-col>
                    <!-- </template> -->
                    <el-col :span="6">
                        <el-form-item
                            label="包装紙產品部位"
                            prop="packagePapperPosition"
                        >
                            <el-select
                                v-model="
                                    state.colorDescForm.packagePapperPosition
                                "
                                :disabled="
                                    state.colorDescForm.isView || isEditing
                                "
                            >
                                <el-option
                                    v-for="item in state.packagePapperPositionList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="物料编号" prop="materialNum">
                            <input
                                :maxlength="40"
                                v-model="state.colorDescForm.materialNum"
                                :disabled="
                                    state.colorDescForm.isView || isEditing
                                "
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="　" prop="isPropertyCode">
                            <el-checkbox
                                v-model="state.colorDescForm.isPropertyCode"
                                :disabled="
                                    state.colorDescForm.isView || isEditing
                                "
                                >特性码</el-checkbox
                            >
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="colorDescDialogCel">取消</el-button>
                    <el-button
                        :loading="state.colorDescFormLoading"
                        type="primary"
                        @click="colorDescDialogSub"
                        :disabled="state.colorDescForm.isView || isEditing"
                    >
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {
    zcbPlateRead,
    getPackagePapperPositionList,
    getArcBendList,
    getSapColor,
    verifySizeColorIsAbilityDeleted
} from "@/api/plmProductSpec";
import { getElectroplateColorCodeList } from "@/api/confElectroplateColorCode";
import { useDict } from "@/utils/dictionary.js";
import { deepClone2, debounce } from "@/utils/tool.js";
import { getChars } from "@/view/plmProductSpec/components/commonFun.js";
import { emitter } from "@/utils/bus.js";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import {
    ref,
    reactive,
    onMounted,
    toRefs,
    watch,
    defineProps,
    defineEmits,
    nextTick,
    computed,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { getProductStylesList } from "@/api/plmProductStyles";
// import * as OpenCC from 'opencc-js';
defineOptions({
    name: "plmProductSpecColorList",
});

let robot = ref(null);

const router = new useRouter();
const route = new useRoute();

const props = defineProps({
    eyeColorData: {
        type: Array,
        default: [],
    },
    formData: {
        type: Object,
        default: {
            customerColorNum: "",
        },
    },
    delType: {
        type: String,
        default: "",
    },
    isEditing: { type: Boolean, default: false },
});
const emit = defineEmits(["getColorList", "colorChangeFun", "copyColor"]);

const eyeColorData1 = ref([]);
const multipleTableRef = ref();

watch(
    () => eyeColorData1.value,
    () => {
        emit("getColorList", deepClone2(eyeColorData1.value));
    },
    { deep: true }
);
watch(
    () => deepClone2(props.formData),
    (newVal, oldVal) => {
        // console.log(newVal, oldVal);
        eyeColorData1.value.forEach((item) => {
            blurTest(item);
            // 颜色编号由生成变为自定义填入先清空
            if (
                (newVal.frameMaterials == "膠架" ||
                    newVal.frameMaterials == "脾架") &&
                oldVal.frameMaterials != "膠架" &&
                oldVal.frameMaterials != "脾架"
            ) {
                item["localColorDesc"] = "";
                item["sapColorParam"] = {};
            }
            if (
                newVal.frameMaterials != "膠架" &&
                newVal.frameMaterials != "脾架" &&
                (oldVal.frameMaterials == "膠架" ||
                    oldVal.frameMaterials == "脾架")
            ) {
                item["localColorDesc"] = "";
                item["sapColorParam"] = {};
            }
        });
    },
    { deep: true }
);

const updateBaseData = () => {
    eyeColorData1.value.forEach((item) => {
        item["customerStyleNum"] = props.formData.customerStyleNum;
    });
};

const colorDescFormRef = ref();
const state = reactive({
    productStylesList: [], //款式列表
    arcBendList: [],
    colorDescDialogFormVisible: false,
    colorDescFormLoading: false,
    colorDescForm: {
        electroplatedColorNum: undefined,
        gradientDesc: "",
        isGradientColor: false,
        gradientColor1: "",
        gradientColor2: "",
        gradientColor3: "",
        gradientColor4: "",
        packagePapperPosition: undefined,
        materialNum: "",
        isPropertyCode: false,
    },
    colorDescFormRules: {
        electroplatedColorNum: [
            // { required: true, message: "请选择电镀色编号", trigger: "blur" },
        ],
        // packagePapperPosition: [
        //     { required: true, message: "请选择", trigger: "blur" },
        // ],
    },
    eyeColorSelectList: [],
});

// 生成本厂颜色描述弹窗打开
function generateColorDesc(index, row) {
    state.colorColum = index;
    state.colorDescDialogFormVisible = true;
    // 电镀色编号
    // zcbPlateRead({}).then((res) => {
    //     state.electroplateColorCodeList = res.data;
    // });
    state.electroplateColorCodeList = [];
    getElectroplateColorCodeList({
        page: 1,
        pageSize: 2000,
    }).then((res) => {
        if (res.code === 0) {
            state.electroplateColorCodeList = res.data.list;
            state.electroplateColorCodeList.unshift({ PLATE: " ", ZDESC: "" });
        }
    });
    // 包装纸产品位置
    useDict(
        "packagePapperPosition" // 新旧
    ).then((res) => {
        state.packagePapperPositionList = res.packagePapperPosition;
    });
    if (row.sapColorParam) {
        state.colorDescForm = { ...row.sapColorParam };
    }
    // state.colorDescForm["isView"] = row.localColorDesc ? true : false;
}

// 颜色弹窗取消
function colorDescDialogCel() {
    state.colorDescDialogFormVisible = false;
    state.colorDescForm = {
        electroplatedColorNum: "",
        gradientDesc: "",
        isGradientColor: false,
        gradientColor1: "",
        gradientColor2: "",
        gradientColor3: "",
        gradientColor4: "",
        packagePapperPosition: "",
        materialNum: "",
        isPropertyCode: false,
    };
}

//颜色弹窗确定
function colorDescDialogSub() {
    colorDescFormRef.value?.validate(async (valid) => {
        if (!valid) return;
        // state.colorDescFormLoading = true;
        // let resL = [];
        // Object.keys(state.colorDescForm).forEach((key) => {
        //     if (
        //         [
        //             "electroplatedColorNum",
        //             "gradientColor1",
        //             "gradientColor2",
        //             "gradientColor3",
        //             "gradientColor4",
        //         ].includes(key) &&
        //         state.colorDescForm[key] &&
        //         state.colorDescForm[key] != " "
        //     ) {
        //         resL.push(state.colorDescForm[key]);
        //     }
        // });
        // state.colorDescFormLoading = false;
        let obj = {};
        obj["electroplatedColorNum"] =
            state.colorDescForm["electroplatedColorNum"];
        obj["gradientColor1"] = state.colorDescForm["gradientColor1"];
        obj["gradientColor2"] = state.colorDescForm["gradientColor2"];
        obj["gradientColor3"] = state.colorDescForm["gradientColor3"];
        obj["gradientColor4"] = state.colorDescForm["gradientColor4"];
        obj["materialNum"] = state.colorDescForm["materialNum"];
        let resL = [];
        Object.keys(obj).forEach((key) => {
            if (obj[key] && obj[key] != " ") {
                resL.push(obj[key]);
            }
        });
        let code = state.colorDescForm.isPropertyCode
            ? resL.join("/") +
              `(${eyeColorData1.value[state.colorColum].colorNum})`
            : resL.join("/");
        code = code.replace(/\s*/g, "");
        let list = eyeColorData1.value.filter((item, index) => {
            return item.localColorDesc == code && state.colorColum != index;
        });
        if (list.length >= 1 && props.delType != 'colors2') {
            // ElMessage({
            //     type: "error",
            //     offset: "25",
            //     message: "当前规格不能有重复的本厂颜色描述",
            // });
            ElNotification({
                title: "当前规格不能有重复的本厂颜色描述",
                type: "error",
                position: "bottom-left",
                customClass: "notification-item-err",
            });
            return;
        }
        // let encoder = new TextEncoder();
        // let bytes = encoder.encode(code).length;
        let bytes = getChars(code)
        if (bytes > 30  && props.delType != 'colors2') {
            // ElMessage({
            //     type: "error",
            //     offset: "25",
            //     message: "本厂颜色描述不能超过30字节",
            // });
            ElNotification({
                title: "本厂颜色描述不能超过30字节",
                type: "error",
                position: "bottom-left",
                customClass: "notification-item-err",
            });
            return;
        }
        eyeColorData1.value[state.colorColum].localColorDesc = code.replace(
            /\s+/g,
            ""
        );
        eyeColorData1.value[state.colorColum]["sapColorParam"] = {
            ...state.colorDescForm,
        };
        colorDescDialogCel();
    });
}

//颜色表格多选
const eyeColorSelectionChange = (val) => {
    state.eyeColorSelectList = val;
    // console.log(state.eyeColorSelectList)
};

//数字转字母
function convertNumberToLetter(num) {
    return String.fromCharCode(num); // 将数字转换为大写字母，其中 A 的 Unicode 值是 65
}

function getCharUnicode(character) {
    return character.charCodeAt(0);
}

// 新增一行颜色
function onAddColor1() {
    let lenList = eyeColorData1.value.filter((item) => {
        return item.colorNum && item.colorNum.length == 1;
    });
    let colorNum = "";
    if (lenList.length == 0) {
        colorNum = "A";
    } else if (0 < lenList.length && lenList.length < 26) {
        for (let i = 0; i < lenList.length; i++) {
            let cur = lenList[i].colorNum.charCodeAt(0);
            if (cur != 65 + i) {
                colorNum = convertNumberToLetter(65 + i);
                break;
            }
        }
        if (colorNum == "") {
            colorNum = convertNumberToLetter(lenList.length);
        }
    } else {
        let lenList2 = eyeColorData1.value.filter((item) => {
            return (
                item.colorNum &&
                item.colorNum.length == 2 &&
                item.colorNum.slice(0, 1) != "Y"
            );
        });
        // console.log(lenList2, lenList2.length);
        let num = lenList2.length;
        colorNum = "A" + convertNumberToLetter(num);
        for (let j = 0; j < lenList2.length; j++) {
            let cur = lenList2[j].colorNum.slice(1, 2).charCodeAt(0);
            if (cur != 65 + j) {
                colorNum = "A" + convertNumberToLetter(65 + i);
                break;
            }
        }
    }
    let timeNum = new Date().getTime();
    eyeColorData1.value.push({
        colorNum: colorNum,
        customerColorNum: "",
        customerStyleNum: props.formData.customerStyleNum,
        localColorDesc: "",
        circleColorRequire: "",
        spleenColorRequire: "",
        otherColorRequire: "",
        idx: colorNum + "-" + timeNum,
    });
    // eyeColorData1.value.sort((a, b) => {
    //     return a.colorNum.localeCompare(b.colorNum);
    // });
    eyeColorData1.value = arrSortFun(eyeColorData1.value);
}
// 新增一行颜色
function onAddColor() {
    let lenList = eyeColorData1.value.filter((item) => {
        return item.colorNum && item.colorNum.length == 1;
    });
    let colorNum = "";
    let cur = 0;
    if (lenList.length > 0) {
        cur = lenList[lenList.length - 1].colorNum.charCodeAt(0);
    }
    let lenList2 = eyeColorData1.value.filter((item) => {
        return (
            item.colorNum &&
            item.colorNum.length == 2 &&
            item.colorNum.slice(0, 1) != "Y"
        );
    });
    console.log(cur);
    if (cur == 0) {
        colorNum = "A";
    } else if (0 < cur && cur < 90) {
        colorNum = convertNumberToLetter(cur + 1);
    } else {
        let curA = 65;
        let start = "A";
        if (lenList2.length > 0) {
            let startB = [
                "AZ",
                "BA",
                "BB",
                "BC",
                "BD",
                "BE",
                "BF",
                "BG",
                "BH",
                "BI",
                "BJ",
                "BK",
                "BL",
                "BM",
                "BN",
                "BO",
                "BP",
                "BQ",
                "BR",
                "BS",
                "BT",
                "BU",
                "BV",
                "BW",
                "BX",
                "BY",
            ];
            let startC = [
                "BZ",
                "CA",
                "CB",
                "CC",
                "CD",
                "CE",
                "CF",
                "CG",
                "CH",
                "CI",
                "CJ",
                "CK",
                "CL",
                "CM",
                "CN",
                "CO",
                "CP",
                "CQ",
                "CR",
                "CS",
                "CT",
                "CU",
                "CV",
                "CW",
                "CX",
                "CY",
            ];
            let startD = [
                "CZ",
                "DA",
                "DB",
                "DC",
                "DD",
                "CE",
                "CF",
                "CG",
                "CH",
                "CI",
                "CJ",
                "CK",
                "CL",
                "CM",
                "CN",
                "CO",
                "CP",
                "CQ",
                "CR",
                "CS",
                "CT",
                "CU",
                "CV",
                "CW",
                "CX",
                "CY",
            ];
            let codeNum = lenList2[lenList2.length - 1].colorNum
                .slice(1, 2)
                .charCodeAt(0);
            if (codeNum < 90) {
                curA = codeNum + 1;
            } else {
                curA = 65;
            }
            if (startB.includes(lenList2[lenList2.length - 1].colorNum)) {
                start = "B";
            } else if (
                startC.includes(lenList2[lenList2.length - 1].colorNum)
            ) {
                start = "C";
            } else if (
                startD.includes(lenList2[lenList2.length - 1].colorNum)
            ) {
                start = "D";
            } else {
                start = "A";
            }
        }
        colorNum = start + convertNumberToLetter(curA);
    }
    let timeNum = new Date().getTime();
    eyeColorData1.value.push({
        colorNum: colorNum,
        customerColorNum: "",
        customerStyleNum: props.formData.customerStyleNum,
        localColorDesc: "",
        circleColorRequire: "",
        spleenColorRequire: "",
        otherColorRequire: "",
        idx: colorNum + "-" + timeNum,
    });
    eyeColorData1.value = arrSortFun(eyeColorData1.value);
}

// 删除当前行颜色
function onDeleteColor(index) {
    let eyeColorData1Pre = deepClone2(eyeColorData1.value);
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        let list = eyeColorData1.value;
        list.splice(index, 1);
        // 重组颜色序号
        list.filter((item) => {
            return (
                (item.colorNum && item.colorNum.length == 1) ||
                (item.colorNum.length == 2 && item.colorNum.slice(0, 1) != "Y")
            );
        }).forEach((item, index) => {
            if (index < 26) {
                item.colorNum = convertNumberToLetter(index);
            } else {
                item.colorNum = "A" + convertNumberToLetter(index - 26);
            }
        });
        list.filter((item) => {
            return (
                item.colorNum.length == 2 && item.colorNum.slice(0, 1) == "Y"
            );
        }).forEach((item, index) => {
            item.colorNum = "Y" + convertNumberToLetter(index);
        });

        // 修改颜色同步修改所关联颜色  ------start
        let colorChangeVal = {};
        eyeColorData1Pre.forEach((colorItem) => {
            let index = eyeColorData1.value.findIndex((val) => {
                return colorItem.idx == val.idx;
            });
            if (index == -1) {
                colorChangeVal[colorItem.colorNum] = null;
            } else {
                colorChangeVal[colorItem.colorNum] =
                    eyeColorData1.value[index].colorNum;
            }
        });
        emit("colorChangeFun", colorChangeVal);
    });
}

// 批量删除颜色
function colorDelete() {
    let eyeColorData1Pre = deepClone2(eyeColorData1.value);
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async() => {
        let selColorStr = state.eyeColorSelectList.map(c=>{
            return c.colorNum
        }).join(',')
        if(route.query.styleNum && selColorStr){
            let param = {
                styleNum: route.query.styleNum,
                colorNum: selColorStr, // sizeNum 和 colorNum 不能同时存在
            };
            let res = await verifySizeColorIsAbilityDeleted(param)
            if(res.code == 0 && !res.data.isDeleted){
                ElNotification({
                    title: "已汇入SAP不能删除",
                    type: "error",
                    position: "bottom-left",
                    customClass: "notification-item-err",
                });
                return
            }else if(res.code != 0){
                ElNotification({
                    title: res.msg || "",
                    type: "error",
                    position: "bottom-left",
                    customClass: "notification-item-err",
                });
                return
            }
        }
        eyeColorData1.value = batchDelete(
            eyeColorData1.value,
            state.eyeColorSelectList
        );
        // 修改颜色同步修改所关联颜色
        let colorChangeVal = {};
        eyeColorData1Pre.forEach((colorItem) => {
            let index = eyeColorData1.value.findIndex((val) => {
                return colorItem.idx == val.idx;
            });
            if (index == -1) {
                colorChangeVal[colorItem.colorNum] = null;
            } else {
                colorChangeVal[colorItem.colorNum] =
                    eyeColorData1.value[index].colorNum;
            }
        });
        emit("colorChangeFun", colorChangeVal);
    });
}

// 批量删除
function batchDelete(arr, itemsToDelete) {
    // 使用filter过滤出不在itemsToDelete数组中的元素
    return arr.filter((item, index) => {
        return itemsToDelete.every((it) => {
            return item.idx != it.idx;
        });
    });
}

// 复制所选颜色外发
function copyYColor() {
    let list = state.eyeColorSelectList.filter((item) => {
        return item.colorNum.length == 1 || item.colorNum.slice(0, 1) != "Y";
    });
    let listCopy = deepClone2(list);
    let timeNum = new Date().getTime();
    listCopy.forEach((item) => {
        let index = eyeColorData1.value.findIndex((val) => {
            return val.colorNum == "Y" + item.colorNum;
        });
        if (index == -1) {
            let obj = JSON.parse(JSON.stringify(item));
            obj["customerColorNum"] = item.customerColorNum + ".";
            obj["localColorDesc"] = item.localColorDesc
                ? item.localColorDesc + "."
                : ".";
            obj["colorNum"] = "Y" + item.colorNum;
            obj["idx"] = "Y" + item.colorNum + timeNum;
            if (obj.ID) delete obj.ID;
            if (item.salesNum) obj["salesNum"] = [];
            blurTest(obj);
            eyeColorData1.value.push(obj);
        }
    });
    eyeColorData1.value = arrSortFun(eyeColorData1.value);
    console.log(eyeColorData1.value);
    multipleTableRef.value.clearSelection();
    state.eyeColorSelectList = [];
}

// 按颜色序号排序
const arrSortFun = (arr) => {
    arr.sort(function (a, b) {
        if (a.colorNum.length === b.colorNum.length) {
            // 如果长度相等，则按字母顺序排序
            return a.colorNum.localeCompare(b.colorNum);
        }
        // 按长度排序
        return a.colorNum.length - b.colorNum.length;
    });
    return arr;
};

// 校验客色号在当前款不能重复，客色号+客款号不能超过30个字节。
const blurTest = (row) => {
    if( props.delType == 'colors2') return
    let list = eyeColorData1.value.filter((item) => {
        let str1 = row.customerColorNum + row.customerStyleNum;
        let str2 = item.customerColorNum + item.customerStyleNum;
        return str1 == str2;
    });
    let str = row.customerColorNum + row.customerStyleNum;
    // let encoder = new TextEncoder();
    // let bytes = encoder.encode(str).length;
    let bytes = getChars(str)
    if (bytes > 30 || list.length > 1) {
        row["err"] =
            list.length > 1
                ? "客色号+客款号不能重复"
                : "客色号+客款号不能超过30个字节";
        // row.customerColorNum = "";
    } else {
        row["err"] = undefined;
    }
};

// 本厂颜色描述不能超过30字节。
const blurLocalColorDescTest = (row) => {
    if( props.delType == 'colors2') return
    let list = eyeColorData1.value.filter((item) => {
        return row.localColorDesc && item.localColorDesc == row.localColorDesc;
    });
    let str = row.localColorDesc;
    // let encoder = new TextEncoder();
    // let bytes = encoder.encode(str).length;
    let bytes = getChars(str)
    if (bytes > 30 || list.length > 1) {
        row["errlocaldesc"] =
            list.length > 1
                ? "本厂颜色描述当前规格不能重复"
                : "本厂颜色描述不能超过30个字节";
        // row.localColorDesc = "";
    } else {
        row["errlocaldesc"] = undefined;
    }
};

// 电镀色改变
const electroplatedColorNumChange = (val) => {
    let index = state.electroplateColorCodeList.findIndex((item) => {
        return item.PLATE == val;
    });
    state.colorDescForm.gradientDesc =
        state.electroplateColorCodeList[index].ZDESC;
};

// 颜色复制
const copyColor = () => {
    emit("copyColor", props.delType);
};

// 是否可选
const selectableHandle = (row, index) => {
    if (row.sapImported === 1) {
        return false;
    }
    return true;
};
const circleColorRequireBlur = (row) =>{
    row['circleColorRequire'] = row.circleColorRequire?.trim() || '';
    // const converter = OpenCC.Converter({ from: 'cn', to: 'hk' });
    // row['circleColorRequire'] = converter(row['circleColorRequire'])
}
const spleenColorRequireBlur = (row) =>{
    row['spleenColorRequire'] = row.spleenColorRequire?.trim() || '';
    // const converter = OpenCC.Converter({ from: 'cn', to: 'hk' });
    // row['spleenColorRequire'] = converter(row['spleenColorRequire'])
}
const otherColorRequireBlur = (row) =>{
    row['otherColorRequire'] = row.otherColorRequire?.trim() || '';
    // const converter = OpenCC.Converter({ from: 'cn', to: 'hk' });
    // row['otherColorRequire'] = converter(row['otherColorRequire'])
}

defineExpose({ updateBaseData });

onMounted(async () => {
    emitter.on("updateColorData", () => {
        eyeColorData1.value = deepClone2(props.eyeColorData);
        eyeColorData1.value.map((item) => {
            item["idx"] = item.ID;
            return item;
        });
        eyeColorData1.value = arrSortFun(eyeColorData1.value);
    });
    // 获取拖拽元素
    nextTick(() => {
        robot.value = document.getElementById("gva-base-load-dom");
    });
});
</script>

<style lang="scss" scoped>
.table-form {
    .el-form-item {
        margin-bottom: 0;
        width: 80%;
    }
}
:deep(.el-form--default.el-form--label-top .el-form-item .el-form-item__label) {
    text-align: left;
}
.sales-num {
    :deep(.el-checkbox) {
        margin: 0;
        &:nth-child(1) {
            margin-right: 8px;
        }
    }
}
:deep(.el-table__header) {
    width: 100% !important;
}
textarea {
    min-height: 32px;
}
</style>